package com.xuecheng.govern.gateway.service;

import com.xuecheng.framework.utils.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author ShengJinFeng
 * @version V1.0
 * @ClassName AuthService
 * @Description (这里用一句话描述这个类的作用)
 * @date 2020/3/12 12:07
 * @since V1.0
 */
@Service
public class AuthService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * @Description 从cookie中获取令牌
     * @author ShengJinFeng
     * @date 2020/3/12
     */
    public String getTokenFromCookie(HttpServletRequest request) {
        Map<String, String> map = CookieUtil.readCookie(request, "uid");
        return map.get("uid");
    }

    /**
     * @Description 从请求头中获取jwt令牌
     * @author ShengJinFeng
     * @date 2020/3/12
     */
    public String getJwkFormHeader(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization) || !StringUtils.startsWith(authorization,"Bearer ")){
            return null;
        }
        return authorization;
    }

    /**
     * @Description 查询令牌过期时间
     * @author ShengJinFeng
     * @date 2020/3/12
     */
    public long getExpire(String accessToken) {
        String key = "user_token:"+accessToken;
        Long expire = stringRedisTemplate.getExpire(key);
        return expire;
    }
}
